import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:convert/convert.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_yres/pages/jiayouzhan/jyz_detail_page.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/model/banner_model.dart';
import 'package:flutter_yres/model/item_model.dart';
import 'package:flutter_yres/model/jiayouList_model.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/tool/BlankToolBarTool.dart';
import 'package:flutter_yres/pages/user/StudyClass.dart';
import 'package:flutter_yres/pages/shop/SearchGoods.dart';
import 'package:flutter_yres/pages/event/LoginEvent.dart';
import 'package:flutter_yres/tool/application.dart';
import 'package:flutter_yres/tool/AppSaveInfoUtil.dart';
import 'package:flutter_yres/pages/car/car_sub_page.dart';
import '../pages/user/InviteFriend.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import '../pages/user/WebPage.dart';
import '../pages/shop/hdk_page.dart';
import 'package:crypto/crypto.dart';
import './login/login_page.dart';
import 'package:flutter_yres/tool/Toast.dart';
import './xiche_page.dart';
import 'package:package_info/package_info.dart';
import 'package:url_launcher/url_launcher.dart';
import '../tool/constant.dart';
import '../main.dart';
import 'package:path_provider/path_provider.dart';
import '../pages/jiayouzhan/goMap.dart';
import '../pages/shop/newPdd.dart';
import '../pages/user/ArticleDetail.dart';
class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class NewsTab {
  String text;
  String state;
  NewsTab(this.text, this.state);
}

class SliverTabBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar widget;
  final Color color;

  const SliverTabBarDelegate(this.widget, {this.color})
      : assert(widget != null);

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return new Container(
      child: widget,
      color: color,
    );
  }

  @override
  bool shouldRebuild(SliverTabBarDelegate oldDelegate) {
    return false;
  }

  @override
  double get maxExtent => widget.preferredSize.height;
  @override
  double get minExtent => widget.preferredSize.height;
}

class _HomePageState extends State<HomePage>
    with
        SingleTickerProviderStateMixin,
        AutomaticKeepAliveClientMixin<HomePage>,
        WidgetsBindingObserver {
  @override
  bool get wantKeepAlive => true;
  List<Widget> list = List();

  double lat, lng;
  String token;
  String rectangle;
  String ip;
  List<BannerModelData> bannerData = []; //轮播图数组
  List<ItemModelData> itemData = []; //功能块数组
  List<JYZModelData> jyzListData = []; //加油站数组
  List<Map> mkdata = [
    {'name': '加油', 'icon': 'images/icon_card_left.png'},
    {'name': '充电', 'icon': 'images/icon_card_right.png'}
  ]; //大模块
  List<BannerModelData> guanggaoData = []; //广告位数组
  //定义tab页基本数据结构
  final List<NewsTab> newsTabs = <NewsTab>[
    new NewsTab('加油', '1'),
    // new NewsTab('充电', '0'),
  ];
  var _currentIndex = 0; //0 是加油站  1是充电站
  EasyRefreshController _controller = new EasyRefreshController();
  BlankToolBarModel barModel = BlankToolBarModel();
  var jyz_selectDistanceItemValue;
  var jyz_selectoilNoItemValue;
  var jyz_selectCondItemValue;
  var jyz_selectGasTypeItemValue;

  int jyz_page = 1;
  //充电站参数
  int cdz_page = 1;

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    super.build(context); //必须添加
    return Scaffold(
        body: BlankToolBarTool.blankToolBarWidget(
      context,
      model: barModel,
      body: new Stack(
        children: <Widget>[
          Container(
            margin: EdgeInsets.fromLTRB(
                0,
                ScreenUtil.getInstance().setWidth(60) +
                    MediaQueryData.fromWindow(window).padding.top +
                    20,
                0,
                0),
            child: new EasyRefresh(
              //刷新  加载组件
              enableControlFinishRefresh: true,
              enableControlFinishLoad: true,
              controller: _controller,
              header: MaterialHeader(),
              footer: MaterialFooter(),
              // refreshHeader:
              //       RefreshUtils.buildBlackClassicsHeader(context, _headerKey),
              // refreshFooter:
              //       RefreshUtils.buildClassicsFooter(context, _footerKey),
              child: CustomScrollView(
                slivers: <Widget>[
                  // 如果不是Sliver家族的Widget，需要使用SliverToBoxAdapter做层包裹
                  SliverToBoxAdapter(
                    child: Container(
                        child: Column(
                      children: <Widget>[
                        _buildBanner(),
                        Container(
                          height: 10,
                        )
                      ],
                    )),
                  ),
                  SliverGrid(
                    gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                      maxCrossAxisExtent:
                          (ScreenUtil.getInstance().setWidth(750) -
                                  ScreenUtil.getInstance().setWidth(20)) /
                              5,
                      mainAxisSpacing: 10.0,
                      crossAxisSpacing: 10.0,
                      childAspectRatio: 0.85, //子控件宽高比
                    ),
                    delegate: SliverChildBuilderDelegate(
                      (BuildContext context, int index) {
                        return _itemBuilder(context, index);
                      },
                      childCount: itemData.length,
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: Container(
                        // height: ScreenUtil.getInstance().setWidth(750) * 0.4 +
                        //     ScreenUtil.getInstance().setHeight(DP_400) +
                        //     ScreenUtil.getInstance().setWidth(30) +
                        //     ScreenUtil.getInstance().setHeight(210) +
                        //     ScreenUtil.getInstance().setWidth(750) * 0.24 +
                        //     ScreenUtil.getInstance().setWidth(20) +
                        //     ScreenUtil.getInstance().setWidth(80) +
                        //     ScreenUtil.getInstance().setHeight(40),
                        child: Column(
                      children: <Widget>[
                        // _buildBanner(),
                        // Container(
                        //   color: Colors.white,
                        //   height: ScreenUtil.getInstance().setHeight(DP_400),
                        //   // margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
                        //   padding: EdgeInsets.all(
                        //       ScreenUtil.getInstance().setHeight(DP_10)),
                        //   child: list.length <= 0
                        //       ? Text('')
                        //       : new GridPage(
                        //           children: list,
                        //           column: 5,
                        //           row: 2,
                        //         ),
                        // ),
                        _buildImageMK(),
                        _buildBanner2(),
                        // _buildTab(),
                        _buildPopHeader()
                      ],
                    )),
                  ),
                  // 当列表项高度固定时，使用 SliverFixedExtendList 比 SliverList 具有更高的性能
                  SliverFixedExtentList(
                      delegate: _buildTypeList(),
                      itemExtent: ScreenUtil.getInstance().setHeight(210)),
                  SliverToBoxAdapter(
                    child: Container(),
                  ),
                ],
              ),
              onRefresh: () async {
                jyz_page = 1;
                loc();
              },
              onLoad: () async {
                jyz_page++;
                _loadList();
              },
            ),
          ),
          _buildSearch(),
        ],
      ),
    ));
  }

  SliverChildDelegate _buildTypeList() {
    if (_currentIndex == 0) {
      //加油站
      return SliverChildBuilderDelegate(_buildListItem,
          childCount: jyzListData.length);
    } else {
      //充电站
      return SliverChildBuilderDelegate(
          (context, index) => ListTile(
                title: Text(
                  'hhhhh',
                  style: TextStyle(fontSize: 20.0),
                ),
              ),
          childCount: 50);
    }
  }

//搜索组件
  _buildSearch() {
    return new Container(
      child: new MaterialButton(
        height: ScreenUtil.getInstance().setWidth(60),
        child: Row(
          children: <Widget>[
            new Icon(Icons.search, color: Colors.grey),
            new Text(
              '点击搜索淘宝商品',
              style: TextStyle(color: Colors.grey),
            ),
          ],
        ),
        onPressed: () {
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new SearchGoodsPage(type: '1');
          }));
        },
        color: Colors.white,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      ),
      width: double.maxFinite,
      // height: kBottomNavigationBarHeight + 40,
      margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
      color: Color.fromRGBO(250, 123, 172, 1),
      padding: EdgeInsets.fromLTRB(
          20, MediaQueryData.fromWindow(window).padding.top, 20, 8),
    );
  }

//轮播图组件
  _buildBanner() {
    return new Container(
      margin: EdgeInsets.only(top: ScreenUtil.getInstance().setWidth(10)),
      width: ScreenUtil.getInstance().setWidth(750),
      height: ScreenUtil.getInstance().setWidth(750) * 0.4,
      child: Swiper(
        itemBuilder: _swiperBuilder,
        itemCount: bannerData.length,
        loop: false,
        autoplay: true,
        autoplayDelay: 15000,
        pagination: new SwiperPagination(
            builder: DotSwiperPaginationBuilder(
          color: Colors.black54,
          activeColor: Colors.white,
        )),
        scrollDirection: Axis.horizontal,
        onTap: (index) {
          //点击轮播图事件
        },
      ),
    );
  }

  Widget _swiperBuilder(BuildContext context, int index) {
    return CachedNetworkImage(
      width: ScreenUtil.getInstance().setWidth(750),
      height: ScreenUtil.getInstance().setWidth(750) * 0.4,
      fit: BoxFit.fill,
      imageUrl: Api.BaseUrl + bannerData[index].img,
      placeholder: (context, url) => Image.asset(
        'images/pic_default.png',
        fit: BoxFit.fill,
        width: ScreenUtil.getInstance().setWidth(750),
        height: ScreenUtil.getInstance().setWidth(750) * 0.4,
      ),
      errorWidget: (context, url, error) => Image.asset(
        'images/pic_default.png',
        width: ScreenUtil.getInstance().setWidth(750),
        height: ScreenUtil.getInstance().setWidth(750) * 0.4,
        fit: BoxFit.fill,
      ),
    );
  }

//功能模块
  // _buildItem() {
  //   return new Container(
  //     color: Colors.white,
  //     height: ScreenUtil.getInstance().setHeight(330),
  //     padding: EdgeInsets.all(3.0),
  //     child: GridView.count(
  //       physics: const NeverScrollableScrollPhysics(),
  //       crossAxisCount: 4,
  //       padding: EdgeInsets.all(5.0),
  //       children: itemData.map((item) {
  //         return _itemBuilder(context, item);
  //       }).toList(),
  //     ),
  //   );
  // }

  Widget _itemBuilder(BuildContext context, int index) {
    return InkWell(
      onTap: () {
        print(itemData[index].id);
        if (itemData[index].id == '1') {
          //洗车ID=1
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) => CarSubPage(
                        pdd_id: '1',
                        name: '洗车',
                        auth: '3',
                      ) //打开第二个页面，并传值，传递值的名称是model
                  ));
        } else if (itemData[index].id == '2') {
          //汽车美容ID=2
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) => CarSubPage(
                      pdd_id: '2',
                      name: '汽车美容',
                      auth: '4') //打开第二个页面，并传值，传递值的名称是model
                  ));
        } else if (itemData[index].id == '3') {
          //汽车维修ID=3
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) => CarSubPage(
                      pdd_id: '3',
                      name: '汽车维修',
                      auth: '5') //打开第二个页面���并传值，传递值的名称是model
                  ));
        } else if (itemData[index].id == '4') {
          //汽车保养ID=4
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) => CarSubPage(
                      pdd_id: '4',
                      name: '汽车保养',
                      auth: '6') //打开第二个页面，并传值，传递值的名称是model
                  ));
        } else if (itemData[index].id == '5') {
          //汽车改装ID=5
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) => CarSubPage(
                      pdd_id: '47',
                      name: '汽车改装',
                      auth: '7') //打开第二个页面，并传值，传递值的名称是model
                  ));
        } else if (itemData[index].id == '6') {
          //淘宝ID=6
          Navigator.of(context).pushNamed("tbCate");
        } else if (itemData[index].id == '7') {
          //天猫ID=7
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new HDKPage(type: '9', name: itemData[index].name);
          }));
        } else if (itemData[index].id == '8') {
          //拼多多ID=8
          // Navigator.of(context).pushNamed("pdd");
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new NewPddPage();
          }));
        } else if (itemData[index].id == '9') {
          //京东ID=9

        } else if (itemData[index].id == '10') {
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new StudyClassPage();
          }));
        } else if (itemData[index].id == '11') {
          //天猫超市ID=11
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new WebPage(
                url: "https://chaoshi.tmall.com/?targetPage=index",
                name: itemData[index].name);
          }));
        } else if (itemData[index].id == '12') {
          //淘宝-9.9包邮ID=12

          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new HDKPage(type: '2', name: itemData[index].name);
          }));
        } else if (itemData[index].id == '13') {
          //淘宝-品牌商品ID=13
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new HDKPage(type: '8', name: itemData[index].name);
          }));
        } else if (itemData[index].id == '14') {
          //拼多多-充值中心ID=14
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new WebPage(
                url: "http://app.yangkeduo.com/deposit.html",
                name: itemData[index].name);
          }));
        } else if (itemData[index].id == '15') {
          getString(UID).then((value) {
            if (value == null || value == '') {
              Navigator.of(context)
                  .push(new MaterialPageRoute(builder: (context) {
                return new LoginPage();
              }));
            } else {
              //365优惠卡券ID=15
              var timestamp = new DateTime.now().millisecondsSinceEpoch;
              Map map = new Map();
              map['machineCode'] = value;
              map["agentId"] = "405";
              map['timestamp'] = "$timestamp";
              List<String> allKeys = [];
              map.forEach((key, value) {
                if (!(value is MultipartFile)) {
                  allKeys.add(key.toString() + '=' + value.toString());
                }
              });
              allKeys.sort((obj1, obj2) {
                return obj1.compareTo(obj2);
              });
              String stringA = allKeys.join("&");
              String stringSignTemp =
                  stringA + "&secretKey=Pe7HRBJYwQfpxCb3s5TGW3hXeWxhXKpH";
              var content = new Utf8Encoder().convert(stringSignTemp);
              var digest = md5.convert(content);
              String pwd = hex.encode(digest.bytes);
              String sign = pwd.toUpperCase();
              Navigator.of(context)
                  .push(new MaterialPageRoute(builder: (context) {
                return new WebPage(
                    url:
                        "http://tq.jfshou.cn/seller/app/classify?machineCode=" +
                            value +
                            "&agentId=405&timestamp=" +
                            "$timestamp" +
                            "&sign=" +
                            sign,
                    name: itemData[index].name);
              }));
            }
          });
        } else if (itemData[index].id == '16') {
          //电商商城ID=16

        } else if (itemData[index].id == '17') {
          //分享海报ID=17
          getString(UID).then((value) {
            if (value == null || value == '') {
              Navigator.of(context).pushNamed("login");
              return;
            }
            Navigator.of(context)
                .push(new MaterialPageRoute(builder: (context) {
              return new InviteFriendPage(
                uid: value,
              );
            }));
          });
        } else if (itemData[index].id == '18') {
          //橙牛洗车
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new WebPage(
                url:
                    "https://wash.chengniu.com/wash/#/home?systemCode=CPH5&activityChannel=zxyd&orderChannel=59",
                name: itemData[index].name);
          }));
        } else if (itemData[index].id == '19') {
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new WebPage(
                url: itemData[index].href, name: itemData[index].name);
          }));
        }
      },
      child: Column(
        children: <Widget>[
          CachedNetworkImage(
            width: ScreenUtil.getInstance().setWidth(90),
            height: ScreenUtil.getInstance().setWidth(90),
            fit: BoxFit.fill,
            imageUrl: Api.BaseUrl + itemData[index].icon,
            placeholder: (context, url) => Image.asset(
              'images/pic_default.png',
              width: ScreenUtil.getInstance().setWidth(90),
              height: ScreenUtil.getInstance().setWidth(90),
              fit: BoxFit.fill,
            ),
            errorWidget: (context, url, error) => Image.asset(
              'images/pic_default.png',
              width: ScreenUtil.getInstance().setWidth(90),
              height: ScreenUtil.getInstance().setWidth(90),
              fit: BoxFit.fill,
            ),
          ),
          Text(
            itemData[index].name,
            style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(24)),
            maxLines: 1,
          )
        ],
      ),
    );
  }

//大模块
  _buildImageMK() {
    return new Container(
      margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
      color: Colors.white,
      height: ScreenUtil.getInstance().setHeight(210),
      padding: EdgeInsets.all(3.0),
      child: GridView.count(
        physics: const NeverScrollableScrollPhysics(),
        crossAxisCount: 2,
        padding: EdgeInsets.all(5.0),
        children: mkdata.map((item) {
          return _imageMKBuilder(context, item);
        }).toList(),
      ),
    );
  }

  Widget _imageMKBuilder(BuildContext context, item) {
    return InkWell(
      onTap: () {
        if (item['name'] == '加油') {
          //跳转到加油
          Navigator.of(context).pushNamed("jyzList");
        }
      },
      child: Column(
        children: <Widget>[
          Image.asset(item['icon']),
        ],
      ),
    );
  }

//广告位组件
  _buildBanner2() {
    // return new Container(
    //   padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
    //   width: ScreenUtil.getInstance().setWidth(750),
    //   height: ScreenUtil.getInstance().setWidth(750) * 0.24,
    //   child: Swiper(
    //     itemBuilder: _swiperBuilder2,
    //     itemCount: guanggaoData.length,
    //     loop: false,
    //     autoplay: true,
    //     autoplayDelay: 15000,
    //     pagination: new SwiperPagination(
    //         builder: DotSwiperPaginationBuilder(
    //       color: Colors.black54,
    //       activeColor: Colors.white,
    //     )),
    //     scrollDirection: Axis.horizontal,
    //     onTap: (index) {
    //       //点击轮播图事件
    //     },
    //   ),
    // );
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
        width: ScreenUtil.getInstance().setWidth(750),
        height: ScreenUtil.getInstance().setWidth(750) * 0.24,
        child: Image.asset(
          'images/banner.png',
          fit: BoxFit.fill,
        ),
      ),
      onTap: () {
        // getString(UID).then((value) {
        //   if (value == null || value == '') {
        //     Navigator.of(context)
        //         .push(new MaterialPageRoute(builder: (context) {
        //       return new LoginPage();
        //     }));
        //   } else {
        //       if(Platform.isAndroid){
        //          const platform = MethodChannel("com.example.flutter_yres/webview");
        // try {
        //   // 调用app地址
        //   platform.invokeMethod(
        //       'install', {"bundleId": "com.example.flutter_yres", "path": ""});
        // } on PlatformException catch (_) {}
        // return ;
        //       }
        Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
          return new JYZPayPage(
              url:
                  "https://wash.chengniu.com/wash/#/home?systemCode=CPH5&activityChannel=zxyd&orderChannel=59",
              name: '洗车');
        }));
        //   }
        // });
      },
    );
  }

  Widget _swiperBuilder2(BuildContext context, int index) {
    return CachedNetworkImage(
      width: ScreenUtil.getInstance().setWidth(750),
      height: ScreenUtil.getInstance().setWidth(750) * 0.24,
      fit: BoxFit.fill,
      imageUrl: Api.BaseUrl + guanggaoData[index].img,
      placeholder: (context, url) => Image.asset(
        'images/pic_default.png',
        fit: BoxFit.fill,
        width: ScreenUtil.getInstance().setWidth(750),
        height: ScreenUtil.getInstance().setWidth(750) * 0.24,
      ),
      errorWidget: (context, url, error) => Image.asset(
        'images/pic_default.png',
        fit: BoxFit.fill,
        width: ScreenUtil.getInstance().setWidth(750),
        height: ScreenUtil.getInstance().setWidth(750) * 0.24,
      ),
    );
  }

//列表tab
  _buildTab() {
    return Container(
      margin:
          EdgeInsets.fromLTRB(0, ScreenUtil.getInstance().setWidth(20), 0, 0),
      width: ScreenUtil.getInstance().setWidth(750),
      height: ScreenUtil.getInstance().setWidth(80),
      // alignment: Alignment.center,
      color: kGrayColor,
      child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: newsTabs.map((item) {
            return GestureDetector(
              //手势监听控件，用于监听各种手势
              child: Container(
                decoration: BoxDecoration(
                  border: Border(
                      bottom: item.state == '1'
                          ? BorderSide(width: 2, color: kDefaultColor)
                          : BorderSide(width: 1, color: kGrayColor)),
                ),
                child: FlatButton(
                  child: Text(item.text,
                      style: item.state == '1'
                          ? TextStyle(
                              fontWeight: FontWeight.w800,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE))
                          : TextStyle()),
                  onPressed: () {
                    setState(() {
                      if (item.text == '加油') {
                        _currentIndex = 0;
                        newsTabs[0].state = '1';
                        newsTabs[1].state = '0';
                      } else {
                        _currentIndex = 1;
                        newsTabs[1].state = '1';
                        newsTabs[0].state = '0';
                      }
                    });
                  },
                ),
              ),
              //onSelectTab函数的使用非常巧妙，
              //相当于定义了一个接口，��操控当前控件以外的数据
            );
          }).toList()),
    );
  }

  _buildPopHeader() {
    //条件筛选头部
    var jyz_header = Container(
      height: ScreenUtil.getInstance().setHeight(40),
      width: ScreenUtil.getInstance().setWidth(750),
      child: Row(
        children: <Widget>[
          // Expanded(
          //     flex: 1,
          //     child: Container(
          //       alignment: Alignment.center,
          //       child: new DropdownButtonHideUnderline(
          //         child: new DropdownButton(
          //           iconSize: 20.0,
          //           hint: new Text(
          //             '距离',
          //             style: TextStyle(
          //               fontSize: ScreenUtil.getInstance().setSp(25),
          //             ),
          //             textAlign: TextAlign.center,
          //           ),
          //           value: jyz_selectDistanceItemValue,
          //           items: jyz_distanceItemList(),
          //           onChanged: (T) {
          //             setState(() {
          //               jyz_selectDistanceItemValue = T;
          //               // _refreshList();
          //               empower();
          //             });
          //           },
          //         ),
          //       ),
          //     )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '油号编码',
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(25)),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectoilNoItemValue,
                    items: jyz_oilNotemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectoilNoItemValue = T;
                        // _refreshList();
                        empower();
                      });
                    },
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '排序',
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(25)),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectCondItemValue,
                    items: jyz_condtemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectCondItemValue = T;
                        // _refreshList();
                        empower();
                      });
                    },
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '加油站类型',
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(25)),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectGasTypeItemValue,
                    items: jyz_gasTypetemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectGasTypeItemValue = T;
                        // _refreshList();
                        empower();
                      });
                    },
                  ),
                ),
              ))
        ],
      ),
    );
    var cdz_header = Container(
      height: ScreenUtil.getInstance().setHeight(40),
      width: ScreenUtil.getInstance().setWidth(750),
      child: Row(
        children: <Widget>[
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '距离',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectDistanceItemValue,
                    items: jyz_distanceItemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectDistanceItemValue = T;
                      });
                    },
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '充电类型',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectDistanceItemValue,
                    items: jyz_distanceItemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectDistanceItemValue = T;
                      });
                    },
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '排序',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectDistanceItemValue,
                    items: jyz_distanceItemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectDistanceItemValue = T;
                      });
                    },
                  ),
                ),
              )),
        ],
      ),
    );
    if (_currentIndex == 0) {
      return jyz_header;
    } else {
      return cdz_header;
    }
  }

//***************************加油站数据列表**************************
  Widget _buildListItem(BuildContext context, int index) {
    return new GestureDetector(
        onTap: () {
          //处理点击事件
          JYZModelData model = jyzListData[index];
          // var gasIds=model.gasid;
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) =>
                      JYZDetailPage(model: model) //打开第二个页面，并传值，传递值的名称是model
                  ));
        },
        child: Container(
            margin: EdgeInsets.fromLTRB(
                0, ScreenUtil.getInstance().setHeight(15), 0, 0),
            child: Column(
              children: <Widget>[
                Row(children: <Widget>[
                  _leftImage(index),
                  Expanded(
                    child: _rightColumn(index),
                  )
                ], crossAxisAlignment: CrossAxisAlignment.start),
                Divider(
                  height: 1,
                )
              ],
            )));
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setWidth(l) ?? 0,
            ScreenUtil.getInstance().setHeight(t) ?? 0,
            ScreenUtil.getInstance().setWidth(r) ?? 0,
            ScreenUtil.getInstance().setHeight(b) ?? 0),
        child: w);
  }

  Widget _leftImage(int index) {
    //左图
    var image = new Image(
        image: NetworkImage(jyzListData[index].gaslogosmall),
        width: ScreenUtil.getInstance().setHeight(150),
        height: ScreenUtil.getInstance().setHeight(150),
        fit: BoxFit.fill);
    return _pd(image, l: 20, t: 0, r: 5, b: 40);
  }

  Widget _rightColumn(int index) {
    //右内容
    var title = Text(
      jyzListData[index].gasname,
      style: TextStyle(color: Colors.black, fontSize:  ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE+3)),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    var price = RichText(
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE))),
        TextSpan(
            text: jyzListData[index].priceyfq,
            style: TextStyle(fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE))),
        TextSpan(
            text: '/升/' + jyzListData[index].oilname,
            style: TextStyle(fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE))),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var distance = RichText(
      text: TextSpan(style: TextStyle(fontSize: 13.0), children: [
        TextSpan(
            text: jyzListData[index].distance == null ||
                    jyzListData[index].distance == ''
                ? ''
                : formatNum(double.parse(jyzListData[index].distance) / 1000, 2)
                        .toString() +
                    'km',
            style: TextStyle(color: Colors.grey)),
        TextSpan(text: '', style: TextStyle(color: Colors.orange)),
      ]),
    );
    var address = Text(
      jyzListData[index].provincename +
          jyzListData[index].cityname +
          jyzListData[index].countyname +
          jyzListData[index].gasaddress,
      style: TextStyle(color: Colors.grey, fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE)),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    return new Column(
      children: <Widget>[
        _pd(title, l: 10, t: 0, r: 10, b: 8),
        Row(
          children: <Widget>[
            _pd(price, l: 10, t: 0, r: 10, b: 8),
            Expanded(
              child: distance,
            ),
            GestureDetector(
                onTap: () {
                   print( jyzListData[index].gasaddresslongitude);
                  print( jyzListData[index].gasaddresslatitude);
                  showDialog(
                      context: context,
                      builder: (context) {
                        return new SimpleDialog(
                          title: new Text("选择地图"),
                          children: <Widget>[
                            new SimpleDialogOption(
                              child: new Text("高德地图"),
                              onPressed: () {
                                MapUtil.gotoAMap(
                                    jyzListData[index].gasaddresslongitude,
                                    jyzListData[index].gasaddresslatitude,
                                    jyzListData[index].gasaddress
                                    );
                              },
                            ),
                            new SimpleDialogOption(
                              child: new Text("百度地图"),
                              onPressed: () {
                                MapUtil.gotoBaiduMap(
                                    jyzListData[index].gasaddresslongitude,
                                    jyzListData[index].gasaddresslatitude,
                                    jyzListData[index].gasaddress
                                    );
                              },
                            ),
                            // new SimpleDialogOption(
                            //   child: new Text("腾讯地图"),
                            //   onPressed: () {
                            //     MapUtil.gotoTencentMap(
                            //         jyzListData[index].gasaddresslongitude,
                            //         jyzListData[index].gasaddresslatitude,
                            //         jyzListData[index].gasaddress
                            //         );
                            //   },
                            // ),
                            new SimpleDialogOption(
                              child: new Text("取消"),
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                          ],
                        );
                      });
                },
                child: Container(
                    margin: EdgeInsets.only(
                        right: ScreenUtil.getInstance().setWidth(10)),
                    child: Text(
                      '导航',
                      style: TextStyle(
                          color: mainColor,
                          fontSize: ScreenUtil.getInstance().setSp(30)),
                    )))
          ],
        ),
        _pd(address, l: 10, t: 0, r: 10, b: 8)
      ],
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

  String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      //小数点后有几位小数
      return (num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString());
    } else {
      return (num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString());
    }
  }

  @override
  void initState() {
    super.initState();
    // downApk("http://www.hpianyi.cn/Public/hpy1.1.5.apk");
    jyz_page = 1;
    checkVersion();
    getBannerList('1'); //轮播
    loadFirstService();
    getBannerList('2'); //广告位
    barModel.outSideCallback = focusNodeChange;
    getString(TOKEN).then((value) {
      setState(() {
        token = value;
        if (value == null || value == '') {
          // isLogin = true;
          // Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
          //   return new LoginPage();
          // }));
        } else {
          loc();
        }
      });
    });
    WidgetsBinding.instance.addObserver(this);
    APPLIC.eventBus.on<LoginEvent>().listen((event) {
      getString(TOKEN).then((value) {
        setState(() {
          token = value;
          if (value == null || value == '') {
            // isLogin = true;
            Navigator.of(context)
                .push(new MaterialPageRoute(builder: (context) {
              return new LoginPage();
            }));
          } else {
            loc();
          }
        });
      });
    });
//安卓上架弹框
    if (Platform.isAndroid)
      getString("ISAGREE").then((value) {
        if (value == null) {
          showDD();
        }
      });
  }

  showDD() {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return new WillPopScope(
              onWillPop: () async => false, //重点此举
              child: AlertDialog(
                  title:
                      Text('油然而省', style: TextStyle(color: Colors.blueAccent)),
                  content: Container(
                    child: Column(
                      children: <Widget>[
                        Text(
                          '谢谢您使用油然而省,我们依据最新的监管要求更新了《用户协议》和《隐私政策》，特向您说明如下：\n1， 为向您提供交易相关的基本功能，我们会收集、使用必要的信息。\n2， 基于您的授权我们可能会获取您的位置等信息，您有权拒绝或取消授权。',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE)),
                        ),
                        Container(
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  Navigator.of(context).push(
                                      MaterialPageRoute(builder: (context) {
                                    return new ArticleDetailPage(
                                      article_id: "1",
                                    );
                                  }));
                                },
                                child: Text(
                                  '《用户协议》',
                                  style: TextStyle(
                                      decoration: TextDecoration.none,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE),
                                      color: Color.fromARGB(255, 67, 181, 41)),
                                ),
                              ),
                              GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  Navigator.of(context).push(
                                      MaterialPageRoute(builder: (context) {
                                    return new ArticleDetailPage(
                                      article_id: "8",
                                    );
                                  }));
                                },
                                child: Text(
                                  '《隐私政策》',
                                  style: TextStyle(
                                      decoration: TextDecoration.none,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE),
                                      color: Color.fromARGB(255, 67, 181, 41)),
                                ),
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                    height: DP_200,
                  ),
                  actions: <Widget>[
                    FlatButton(
                        child: Text("同意使用"),
                        onPressed: () {
                          saveString("ISAGREE", "1");
                          Navigator.of(context).pop(1);
                        }),
                    FlatButton(
                        child: Text("拒绝",
                            style: TextStyle(
                                color: black_99,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(NORMAL_FONT_SIZE))),
                        onPressed: () {
                          SystemChannels.platform
                              .invokeMethod('SystemNavigator.pop');
                        })
                  ]));
        });
  }

  loc() async {
    if (Platform.isIOS) {
      // abloc();
      final location = await AmapLocation.fetchLocation();
        // location.latLng.then((value) {
        //   lat = value.latitude;
        //   lng = value.longitude;
        //   empower();
        // });
         setState(() {
 lat = location.latLng.latitude;
          lng = location.latLng.longitude;
          empower();
        });
    } else if (Platform.isAndroid) {
      PermissionStatus permission = await PermissionHandler()
          .checkPermissionStatus(PermissionGroup.location);
      if (permission == PermissionStatus.granted) {
        final location = await AmapLocation.fetchLocation();
        // location.latLng.then((value) {
        //   lat = value.latitude;
        //   lng = value.longitude;
        //   empower();
        // });
        setState(() {
 lat = location.latLng.latitude;
          lng = location.latLng.longitude;
          empower();
        });
      } else if (permission == PermissionStatus.neverAskAgain ||
          permission == PermissionStatus.denied) {
        await PermissionHandler()
            .requestPermissions([PermissionGroup.location]);
        loc();
        // _controller.finishLoad();
        // _controller.finishRefresh();
        // print('永不询问');
        // showDialog<Null>(
        //   context: context,
        //   barrierDismissible: false,
        //   builder: (BuildContext context) {
        //     return SimpleDialog(
        //       title: Text('提示'),
        //       shape: BeveledRectangleBorder(
        //         borderRadius: BorderRadius.all(Radius.circular(10.0)),
        //         side: BorderSide.none),
        //         children: <Widget>[
        //       //不用SimpleDialogOption，就不会遵循SimpleDialog的间距
        //       SimpleDialogOption(
        //         child: Text("您未开启‘油然而省’定位权限，请去系统设置开启"),
        //       ),
        //       SimpleDialogOption(
        //         child: Row(
        //           mainAxisAlignment: MainAxisAlignment.end,
        //           children: <Widget>[
        //             RaisedButton(
        //               child: Text("知道了"),
        //               onPressed: () => {
        //                     Navigator.of(context).pop() //关闭弹框
        //                   },
        //             )
        //           ],
        //         ),
        //       ),
        //     ],
        //       );
        //   },
        // );
      } else {
        _controller.finishLoad();
        _controller.finishRefresh();
        await PermissionHandler()
            .requestPermissions([PermissionGroup.location]);
        loc();
      }
    }
  }

  abloc() async {
    String url =
        "https://webapi.amap.com/maps/ipLocation?key=7a608be3db2f08377a8dbc098421ab64&callback=jsonp_199126_&csid=6E386226-2410-470F-B0C5-09D7DE9CF03F";
    Response<String> response = await HttpUtil().get(url);
    List s = response.data.split('jsonp_199126_(');
    List s2 = s[1].split(')');
    Map userMap = json.decode(s2[0]);
    setState(() {
      if (userMap['status'].toString() == '1') {
        lat = double.parse(userMap['lat']);
        lng = double.parse(userMap['lng']);
        // _refreshList();
        empower();
      } else {
        bloc();
      }
    });
  }

  bloc() async {
    String url = "https://ip.seeip.org/geoip";
    Response<String> response = await HttpUtil().get(url);
    Map userMap = json.decode(response.data);
    setState(() {
      ip = userMap['ip'];
      cloc(ip);
    });
  }

  cloc(String theip) async {
    String url =
        'https://restapi.amap.com/v3/ip?output=json&key=fc9ab3e41e05ebc633244a07a83e1b1f&ip=' +
            theip;
    Response<String> response = await HttpUtil().get(url);
    Map userMap = json.decode(response.data);
    setState(() {
      if (userMap['status'].toString() == '1') {
        List s = userMap['rectangle'].toString().split(';');
        rectangle = s[0];
        // _refreshList();
        empower();
        //  lat = userMap['latitude'];
        // lng = userMap['longitude'];
      }
    });
  }

  void focusNodeChange() {
    setState(() {});
  }

  @override
  void dispose() {
    // AMapLocationClient.shutdown();
    super.dispose();
    barModel.removeFocusListeners();
    WidgetsBinding.instance.removeObserver(this); //销毁观察者
  }

/*网络请求************/
/*轮播图*/
  getBannerList(String Cat_id) async {
    FormData data = new FormData.fromMap({'cat_id': Cat_id});
    Response<String> response =
        await HttpUtil().post(Api.GetBannerListUrl, data: data);
    Map userMap = json.decode(response.data);
    BannerModelEntity bannerEntity = new BannerModelEntity.fromJson(userMap);
    if (bannerEntity.code == 1) {
      if (mounted) {
        setState(() {
          if (Cat_id == '1') {
            //顶���轮播
            bannerData.clear();
            bannerData = bannerEntity.data;
          } else if (Cat_id == '2') {
            //广告位
            guanggaoData.clear();
            guanggaoData = bannerEntity.data;
          }
        });
      }
    }
  }

  empower() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    Map map = new Map();
    map['phone'] = preferences.get("name");
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.kGetEmpowerURL, data: data);
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1) {
      if (mounted) {
        // if (jyz_page == 1) {
        _refreshList();
        // } else {
        //   _loadList();
        // }
      }
    }
  }

  void _refreshList() {
    jyz_page = 1;
    getJYStationList(jyz_selectGasTypeItemValue, null, jyz_selectoilNoItemValue,
        jyz_selectCondItemValue);
  }

  void _loadList() {
    // setState(() {
    jyz_page++;
    getJYStationList(jyz_selectGasTypeItemValue, jyz_selectDistanceItemValue,
        jyz_selectoilNoItemValue, jyz_selectCondItemValue);
    // });
  }

/*加油站列表数据*/
/*获取列表数据*/
  getJYStationList(gasType, distinct, oilNo, cond) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    //���油站

    Map map = new Map();
    // map['token']=token;
    map['phone'] = preferences.get("name");
    map['page'] = jyz_page.toString();
    map['per'] = '4';
    map['cond'] = '2';
    if (distinct != null) {
      map['distinct'] = distinct;
    }
    if (cond != null) {
      map['cond'] = cond;
    }
    if (gasType != null) {
      map['gasType'] = gasType;
    }
    if (lat != null) {
      map['lng_lat'] = lng.toString() + "," + lat.toString();
    }
    if (rectangle != null) {
      map['lng_lat'] = rectangle;
    }
    
    print(map);
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.kGetGasoilURL, data: data);
    Map userMap = json.decode(response.data);
    JYZModelEntity jyzEntity = new JYZModelEntity.fromJson(userMap);
    // Toast.toast(context, msg: userMap['msg']);
    if (jyzEntity.code == 1) {
      if (mounted) {
        print('========加油站========');
        print(userMap);
        setState(() {
          if (jyz_page == 1) {
            jyzListData.clear();
            jyzListData.addAll(jyzEntity.data);
            _controller.finishRefresh();
            _controller.finishLoad();
          } else {
            jyzListData.addAll(jyzEntity.data);
            _controller.finishLoad();
            _controller.finishRefresh();
          }
        });
      }
    } else {
      _controller.finishRefresh();
      _controller.finishLoad();
    }
  }

  /*样式配置*/
  getItemList() async {
    FormData data = new FormData.fromMap({});
    Response<String> response = await HttpUtil().post(Api.SetUrl, data: data);
    Map userMap = json.decode(response.data);
    ItemModelEntity itemEntity = new ItemModelEntity.fromJson(userMap);
    if (itemEntity.code == 0) {
      if (mounted) {
        setState(() {
          itemData.clear();
          itemData = itemEntity.data;
        });
      }
    }
  }

  loadFirstService() async {
    //首页模块
    try {
      FormData data = new FormData.fromMap({});
      Response<String> response = await HttpUtil().post(Api.SetUrl, data: data);
      Map userMap = json.decode(response.toString());
      var naviEntity = ItemModelEntity.fromJson(userMap);
      if (userMap['code'] == 0 && mounted) {
        setState(() {
          itemData.clear();
          itemData.addAll(naviEntity.data);
          list.clear();
        });
      }
    } catch (e) {
      print(e);
    }
  }

  //加油站参数
  List<DropdownMenuItem> jyz_distanceItemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1000',
        child: new Text(
          '1千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '3000',
        child: new Text(
          '3千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '5000',
        child: new Text(
          '5千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '10000',
        child: new Text(
          '10千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  List<DropdownMenuItem> jyz_oilNotemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '92',
        child: new Text(
          '#92',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '95',
        child: new Text(
          '#95',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '98',
        child: new Text(
          '#98',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '0',
        child: new Text(
          '#0',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  List<DropdownMenuItem> jyz_condtemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1',
        child: new Text(
          '油价升序',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '2',
        child: new Text(
          '距离升序',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    return items;
  }

  List<DropdownMenuItem> jyz_gasTypetemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1',
        child: new Text(
          '中石油',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '2',
        child: new Text(
          '中石化',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '3',
        child: new Text(
          '壳牌',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '4',
        child: new Text(
          '其他',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  checkVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    int versionCode = int.parse(packageInfo.version.replaceAll(".", ""));
    // print('=========当前版本=========');
    // print(versionCode);
    Map map = new Map();
    // map['sign_type'] = SignType.CHECK_VERSION;
    Response<String> response =
        await HttpUtil().post(Api.GetVersionUrl, data: {});
    Map userMap = json.decode(response.data);
    print('=========版本检查=========');
    print(userMap);
    if (userMap['code'] == 0 && mounted) {
      if (Platform.isAndroid) {
        //  print('=========是安卓=========');
        PermissionStatus permission = await PermissionHandler()
            .checkPermissionStatus(PermissionGroup.storage);
        if (permission == PermissionStatus.granted) {
          // print('=========读取权限授权成功=========');
        } else {
          await PermissionHandler()
              .requestPermissions([PermissionGroup.storage]);
          checkVersion();
          // print('=========读取权限授权失败=========');
          return;
        }
        // print('=========可以版本检查=========');
        int service = int.parse(
            userMap['data']['version_android'].toString().replaceAll(".", ""));
        if (service > versionCode) {
          //做更新处理
          showDialog(
            context: context,
            builder: (context) => new AlertDialog(
              title: new Text('提示'),
              content:
                  new Text('应用发现新的版本，是否下载更新\n' + userMap['data']['content']),
              actions: <Widget>[
                new FlatButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: new Text(
                    '取消',
                    style: TextStyle(color: Colors.grey),
                  ),
                ),
                new FlatButton(
                  onPressed: () async {
                    downApk(userMap['data']['down_android']);
                    Navigator.of(context).pop(false);
                  },
                  child: new Text('立即下载', style: TextStyle(color: mainColor)),
                ),
              ],
            ),
          );
        }
      } else {
        int service = int.parse(
            userMap['data']['version_ios'].toString().replaceAll(".", ""));
        if (service > versionCode) {
          //做更新处理
          showDialog(
            context: context,
            builder: (context) => new AlertDialog(
              title: new Text('提示'),
              content: new Text('应用发现新的版本，是否前去下载'),
              actions: <Widget>[
                new FlatButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: new Text(
                    '取消',
                    style: TextStyle(color: Colors.grey),
                  ),
                ),
                new FlatButton(
                  onPressed: () async {
                    final url =
                        "https://itunes.apple.com/cn/app/id1504170754"; // id 后面的数字换成自己的应用 id 就行了
                    if (await canLaunch(url)) {
                      await launch(url, forceSafariVC: false);
                    } else {
                      throw 'Could not launch $url';
                    }
                    Navigator.of(context).pop(false);
                  },
                  child: new Text('立即前往', style: TextStyle(color: mainColor)),
                ),
              ],
            ),
          );
        }
      }
    }
  }

  double percent = 0;
  downApk(String url) async {
    Directory dic;
    dic = await getExternalStorageDirectory();
    Response response;
    File file = File(dic.path +
        "/" +
        DateTime.now().millisecondsSinceEpoch.toString() +
        ".apk");
    if (!file.existsSync()) {
      file.createSync();
    }
    show();
    try {
      response = await new Dio().download(url, file.path,
          onReceiveProgress: (int count, int total) {
        // //进度
        // _showNotification(
        //     (count * 100 / total).toString().substring(0, 5) + '%');
        percent = count * 1.00 / total;
        print(count * 100.00 / total);
        if (total - count <= 10) {
          Navigator.of(context).pop(1);
        }
        mystate(() {});
      });
      if (response.statusCode == 200) {
        _installApk(file.path);
        // flutterLocalNotificationsPlugin.cancelAll();

        // Fluttertoast.showToast(msg: '下载成功');
      }
      // print('downloadFile success---------${response.data}');
    } on DioError catch (e) {
      Toast.toast(context, msg: '下载出错');
      // print('downloadFile error---------$e');
    }
  }

  var mystate;
  show() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => new StatefulBuilder(
        builder: (context, setState) {
          mystate = setState;
          return new AlertDialog(
            title: Text('下载进度'),
            content: new LinearProgressIndicator(
              value: percent,
              valueColor: new AlwaysStoppedAnimation<Color>(mainColor),
              backgroundColor: Colors.grey,
            ),
          );
        },
      ),
    );
  }

  Future _showNotification(String str) async {
    //安卓的通知配置，必填参数是渠道id, 名称, 和描述, 可选填通知的图标，重要度等等。
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
        "1", 'yres', 'yres',
        importance: Importance.Max, priority: Priority.High);
    //IOS的通知配置
    var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
    var platformChannelSpecifics = new NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    //显示通知，其中 0 代表通知的 id，用于区分通知。
    await flutterLocalNotificationsPlugin.show(
        0, '更新服务正在运行', '已下载$str', platformChannelSpecifics,
        payload: 'complete');
  }

  // 调用android代码安装apk
  void _installApk(String path) {
    const platform = MethodChannel("com.example.flutter_yres/update");
    try {
      // 调用app地址
      platform.invokeMethod(
          'install', {"bundleId": "com.example.flutter_yres", "path": path});
    } on PlatformException catch (_) {}
  }
}
